<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者姓名" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入患者姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            :icon="Plus"
            @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            :icon="Delete"
            @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="患者编号" align="center" width="100" type="index" />
      <el-table-column label="患者姓名" align="center" prop="name" />
      <el-table-column label="联系电话" align="center" prop="phoneNumber" />
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="{ row }">
          {{ row.gender === 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column label="所属医生" align="center" prop="doctors.name" />
      <el-table-column label="疾病类型" align="center" prop="diseaseType" />
      <el-table-column label="患者状态" align="center" prop="recoveryStatus">
        <template #default="{ row }">
          <if>
            <if v-if="row.recoveryStatus === 1">
              康复中
            </if>
            <if v-if="row.recoveryStatus === 2">
              已康复
            </if>
            <if v-if="row.recoveryStatus === 3">
              治疗中
            </if>
            <if v-if="row.recoveryStatus === 4">
              未康复
            </if>
          </if>
        </template>
      </el-table-column>
      <el-table-column label="医嘱" align="center" prop="remarks" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <if>
            <if v-if="row.recoveryStatus===2">
              <el-button type="primary" link :icon="Edit" @click="handleFeedback(row)">患者反馈</el-button>
            </if>
            <if v-if="row.recoveryStatus!=2">
              <el-button type="primary" link :icon="Edit" @click="handleUpdate(row)">修改</el-button>
            </if>
          </if>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-if="total > 0"
        v-model:current-page="queryParams.currentPage"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[3, 5, 10, 20]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 添加/修改对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="患者姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入患者姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属医生" prop="doctorid">
          <el-select
              v-model="form.doctorid"
              placeholder="请选择医生"
              clearable
          >
            <el-option
                v-for="item in doctorsList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="患者状态" prop="recoveryStatus">
          <el-select v-model="form.recoveryStatus" placeholder="请选择状态">
            <el-option label="康复中" :value="1" />
            <el-option label="已康复" :value="2" />
            <el-option label="治疗中" :value="3" />
            <el-option label="未康复" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="疾病类型" prop="diseaseType">
          <el-input v-model="form.diseaseType" placeholder="请输入疾病类型" />
        </el-form-item>
        <el-form-item label="医嘱" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入医嘱信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加患者反馈对话框 -->
    <el-dialog title="患者反馈" v-model="feedbackOpen" width="500px" append-to-body>
      <el-form ref="feedbackFormRef" :model="feedbackForm" :rules="feedbackRules" label-width="100px">
        <el-form-item label="评分" prop="rating">
          <el-rate
            v-model="feedbackForm.rating"
            :texts="['极差', '失望', '一般', '满意', '惊喜']"
            show-text
          />
        </el-form-item>
        <el-form-item label="评价内容" prop="evaluationContent">
          <el-input
            v-model="feedbackForm.evaluationContent"
            type="textarea"
            :rows="4"
            placeholder="请输入评价内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFeedback">确 定</el-button>
          <el-button @click="feedbackOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { listInfo, getInfo, delInfo, updateInfo,getDoctors ,addPatient,submitPatientFeedback} from '../../api/patient/patient.js'

// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 患者表格数据
const infoList = ref([])
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 表单引用
const formRef = ref(null)
const queryFormRef = ref(null)

// 查询参数
const queryParams = ref({
  currentPage: 1,
  pageSize: 5,
  name: '',
  queryString:''
})
const selectQueryCondition = () => {
  if (queryParams.value.name) {
    queryParams.value.queryString = queryParams.value.name;
  } else {
    queryParams.value.queryString = null;
  }
};

// 表单参数
const form = reactive({
  id: 0,
  name: '',
  phoneNumber: '',
  gender: 1,
  doctorid: undefined,
  recoveryStatus: 1,
  diseaseType: '',
  remarks: ''
})
const doctorsList = ref([])
const getDoctorsList = async () => {
  try {
    const res = await getDoctors()
    if (res && res.flag && res.data) {
      doctorsList.value = res.data || []
    } else {
      doctorsList.value = []
      ElMessage.warning(res?.message || '暂无医生数据')
    }
  } catch (error) {
    console.error('获取医生列表失败:', error)
    ElMessage.error('获取医生列表失败')
  }
}

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '患者姓名不能为空', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '联系电话不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
}

// 查询列表
const getList = async () => {
  selectQueryCondition()
  loading.value = true
  try {
    const res = await listInfo(queryParams.value)
    console.log('患者列表响应:', res)
    if (res && res.rows && Array.isArray(res.rows)) {  // 检查 res.rows 是否为数组
      infoList.value = res.rows
      total.value = res.total || 0
      console.log('设置后的患者列表:', infoList.value)
      if (infoList.value.length === 0) {
        ElMessage.warning('暂无患者数据')
      }
    } else {
      infoList.value = []
      total.value = 0
      ElMessage.warning('获取数据失败，返回数据格式不正确')
    }
  } catch (error) {
    console.error('获取患者列表失败:', error)
    infoList.value = []
    total.value = 0
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 表单重置
const reset = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    id: 0,
    name: '',
    phoneNumber: '',
    gender: 1,
    doctorid: undefined,
    recoveryStatus: 1,
    diseaseType: '',
    remarks: ''
  })
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加患者'
}

// 修改按钮操作
const handleUpdate = async (row) => {
  reset()
  const id = row.id
  try {
    const res = await getInfo(id)
    console.log('获取患者详情响应:', res)
    if (res && res.flag && res.data) {
      // 直接使用返回的数据
      Object.assign(form, {
        id: res.data.id,
        name: res.data.name,
        phoneNumber: res.data.phoneNumber,
        gender: res.data.gender,
        doctorid: res.data.doctorid,
        recoveryStatus: res.data.recoveryStatus,
        diseaseType: res.data.diseaseType,
        remarks: res.data.remarks
      })
      open.value = true
      title.value = '修改患者'
    } else {
      ElMessage.warning(res?.message || '未获取到患者信息')
    }
  } catch (error) {
    console.error('获取患者详情失败:', error)
    ElMessage.error('获取患者信息失败')
  }
}

// 提交按钮
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    let res

    if (form.id) {
      // 修改操作保持不变
      console.log('提交的修改表单数据:', form)
      res = await updateInfo(form)
      console.log('修改响应:', res)
      if (res && res.flag) {
        ElMessage.success(res.message || '修改成功')
        open.value = false
        await getList()
      } else {
        ElMessage.error(res?.message || '修改失败')
      }
    } else {
      // 新增操作
      console.log('提交的新增表单数据:', form)

      // 记录添加前的列表长度
      const beforeCount = infoList.value.length

      res = await addPatient(form)
      console.log('新增响应:', res)

      // 刷新列表
      await getList()

      // 通过比较列表长度来判断是否真正添加成功
      if (infoList.value.length > beforeCount) {
        ElMessage.success('添加成功')
        open.value = false
      } else {
        // 再次检查最新数据中是否包含刚添加的患者信息
        const isAdded = infoList.value.some(
            item => item.name === form.name &&
                item.phoneNumber === form.phoneNumber
        )

        if (isAdded) {
          ElMessage.success('添加成功')
          open.value = false
        } else {
          ElMessage({
            message: '添加可能未成功，请检查数据是否正确添加',
            type: 'warning'
          })
          console.log('添加操作响应:', res)
        }
      }
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error(error?.message || '操作失败，请稍后重试')
  }
}

// 删除按钮操作
const handleDelete = async (row) => {
  const deleteIds = row?.id || ids.value
  if (!deleteIds || (Array.isArray(deleteIds) && !deleteIds.length)) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  try {
    await ElMessageBox.confirm('是否确认删除选中的数据项？')
    const res = await delInfo(deleteIds)
    if (res && res.flag) {
      ElMessage.success(res.message || '删除成功')
      await getList()  // 确保列表更新
    } else {
      ElMessage.error(res?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  getList();
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.currentPage = val;
  getList();
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 添加新的响应式变量
const feedbackOpen = ref(false)
const feedbackFormRef = ref(null)
const feedbackForm = reactive({
  id: 0,
  patientId: 0,
  rating: 5,
  evaluationContent: '',
  mobileNumber: '',
  doctorId: 0
})

// 添加反馈表单验证规则
const feedbackRules = {
  rating: [
    { required: true, message: '请选择评分', trigger: 'change' }
  ],
  evaluationContent: [
    { required: true, message: '请输入评价内容', trigger: 'blur' }
  ]
}

// 修改操作栏的点击事件
const handleFeedback = (row) => {
  feedbackForm.id = row.id
  feedbackForm.patientId = row.id
  feedbackForm.doctorId = row.doctors.id
  feedbackForm.mobileNumber = row.phoneNumber
  feedbackOpen.value = true
}

// 提交反馈
const submitFeedback = async () => {
  if (!feedbackFormRef.value) return

  try {
    await feedbackFormRef.value.validate()
    // TODO: 这里需要添加提交反馈的API调用
    const res = await submitPatientFeedback(feedbackForm)
    if(res.flag==true){
      ElMessage.success('提交成功')
      feedbackOpen.value = false
      // 重置表单
      feedbackForm.rating = 5
      feedbackForm.evaluationContent = ''
      feedbackForm.patientId = null
      feedbackForm.doctorId = null
      feedbackForm.mobileNumber=''
    }else{
      ElMessage.error('提交失败，请重试')
      feedbackOpen.value = false
    }
  } catch (error) {
    console.error('提交反馈失败:', error)
    ElMessage.error('提交失败，请重试')
  }
}

onMounted(() => {
  getList()
  getDoctorsList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.dialog-footer {
  padding: 20px;
  text-align: right;
}
</style>
